<template>
  <el-dialog title="选择物料"
             v-if="showFlag"
             :visible.sync="showFlag"
             :modal=false
             width="80%"
             center
  >
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="物料名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="物料编码" prop="itemCode">
          <el-input
            v-model="queryParams.itemCode"
            placeholder="请输入物料编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料识别码" prop="itemIdentifyCode">
          <el-input
            v-model="queryParams.itemIdentifyCode"
            placeholder="请输入物料识别码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="物料分类" prop="classId">
          <el-select style="width: 100%" v-model="queryParams.classId" placeholder="请选择物料分类">
            <el-option
              v-for="dict in classOptions"
              :key="dict.classId"
              :label="dict.className"
              :value="dict.classId"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="供应商" prop="supplyId">
          <el-select style="width: 100%" v-model="queryParams.supplyId" placeholder="供应商">
            <el-option
              v-for="dict in supplyOptions"
              :key="dict.id"
              :label="dict.supplyName"
              :value="dict.id"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="demoTable" height="calc(100vh - 300px)" v-loading="loading" :data="iteminfoList" @current-change="handleCurrent">
        <el-table-column width="55" align="center">
          <template v-slot="scope">
            <el-radio v-model="selectedItemId" :label="scope.row.id" @change="handleRowChange(scope.row)">{{ "" }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="公司代码" align="center" prop="factoryCode" class-name="small-padding fixed-width"/>
        <el-table-column label="公司名称" align="center" prop="factoryName" class-name="small-padding fixed-width"/>
        <el-table-column width="220" label="物料编号" align="center" prop="itemCode"/>
        <el-table-column width="220" label="物料子编号" align="center" prop="itemId"/>
        <el-table-column label="物料名称" width="220" show-overflow-tooltip align="center" prop="itemName"/>
        <el-table-column label="物料识别码" width="250" show-overflow-tooltip align="center" prop="itemIdentifyCode"/>
        <el-table-column label="物料单位" align="center" prop="unit">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.jc_iteminfo_unit" :value="scope.row.unit"/>
          </template>
        </el-table-column>
        <el-table-column label="规格型号" show-overflow-tooltip align="center" prop="spec" width="220"/>
        <el-table-column width="150" label="条码号" align="center" prop="tmh"/>
        <el-table-column label="物料分类编码" align="center" prop="classId"/>
        <el-table-column label="物料分类名称" align="center" prop="className"/>
        <el-table-column label="物料大类编码" align="center" prop="classBigId"/>
        <el-table-column label="物料大类名称" align="center" prop="classBigName"/>
        <el-table-column label="供应商编码" align="center" prop="supplyId"/>
        <el-table-column label="供应商名称" align="center" prop="supplyName"/>
        <el-table-column label="供应商类别" align="center" prop="supplyType"/>
        <el-table-column label="供应商简称" align="center" prop="supplyJc"/>
        <el-table-column label="预警上线" align="center" prop="upLine"/>
        <el-table-column label="预警下线" align="center" prop="downLine"/>
        <el-table-column label="中间值" align="center" prop="middleLine"/>
        <el-table-column label="存储期" align="center" prop="cunchudate"/>
        <el-table-column label="保质期" align="center" prop="productiondate"/>
        <el-table-column label="尺寸" align="center" prop="size"/>
        <el-table-column label="单重" align="center" prop="singleWeight"/>
        <el-table-column label="使用状态" align="center" prop="useState"/>
        <el-table-column label="颜色" align="center" prop="color"/>
        <el-table-column label="花纹" align="center" prop="figure"/>
        <el-table-column label="材质" align="center" prop="caizhi"/>
        <el-table-column label="包装数量" align="center" prop="baozhuangQty"/>
        <el-table-column label="包装方式" align="center" prop="baozhuangType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.jc_iteminfo_bz" :value="scope.row.baozhuangType"/>
          </template>
        </el-table-column>
        <el-table-column label="物料状态" align="center" prop="stopFlag">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.jc_iteminfo_stop" :value="scope.row.stopFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="组织机构" align="center" prop="deptId"/>
        <el-table-column label="托管状态" align="center" prop="isTuoguan">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.is_tuoguan" :value="scope.row.isTuoguan"/>
          </template>
        </el-table-column>
        <el-table-column label="成本价" align="center" prop="price"/>
        <el-table-column label="计划价" align="center" prop="jhPrice"/>
        <el-table-column label="合同价" align="center" prop="htPrice"/>
        <el-table-column label="发票价" align="center" prop="fpPrice"/>
        <el-table-column label="结算价" align="center" prop="jsPrice"/>
        <el-table-column label="生产周期" align="center" prop="proCycle"/>
        <el-table-column label="供货周期" align="center" prop="deliveryCycle"/>
        <el-table-column label="供货份额" align="center" prop="deliveryFe"/>
        <el-table-column label="份额调整比例" align="center" prop="adjustRate"/>
        <el-table-column label="份额调整日期" align="center" prop="adjustDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.adjustDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="月订单数量" align="center" prop="yddNum"/>
        <el-table-column label="月完成数量" align="center" prop="ywcNum"/>
        <el-table-column label="月度供货未完成比率" align="center" prop="yghwwcRate"/>
        <el-table-column label="生产线简码" align="center" prop="lineSimpleCode"/>
        <el-table-column label="备注" align="center" prop="remark"/>

      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelect">确 定</el-button>
        <el-button @click="showFlag=false">取 消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {listIteminfo, getIteminfo, delIteminfo, delAllItemInfo, addIteminfo, updateIteminfo} from "@/api/base/iteminfo";
import {getToken} from "@/utils/auth";
import {getListClass} from "@/api/base/class";
import {getListBigClass} from "@/api/base/iteminfoClassBig";
import {getLiSupplier} from "@/api/supplychain/supplier";
import {getLodop} from "@/common/LodopFuncs";
import QRCode from "qrcodejs2";
import print from 'print-js';

export default {
  name: "Iteminfo",
  dicts: ['jc_iteminfo_unit', 'jc_iteminfo_bz', 'jc_iteminfo_stop', 'is_tuoguan'],
  data() {
    var validateitemCode = (rule, value, callback) => {
      var reg = /^.{0,50}$/;
      if (!reg.test(value) && value != undefined && value != "") {
        return callback(new Error('物料编号过长!'));
      } else {
        callback();
      }
    };

    var validateupLine = (rule, value, callback) => {
      var reg = /^\+?(0|[1-9][0-9]*)$/
      if (!reg.test(value) && value != undefined && value != "") {
        return callback(new Error('预警值只能是整数!'));
      } else {
        callback();
      }
    };

    return {
      showFlag: false,
      selectedItemId: undefined,
      selectedRows: undefined,
      formDan: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      jms: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料信息表格数据
      iteminfoList: [],
      options: [{
        value: '0',
        label: '下料线'
      }, {
        value: '1',
        label: '1吨线'
      }, {
        value: '2',
        label: '750线'
      }, {
        value: '3',
        label: '560线'
      }, {
        value: '4',
        label: '250线'
      }],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //分类类单位字典
      classOptions: [],
      //大类单位字典
      classBigOptions: [],
      //供应商字典
      supplyOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        itemName: null,
        unit: null,
        baozhuangType: null,
        baozhuangQty: null,
        spec: null,
        model: null,
        tmh: null,
        classId: null,
        className: null,
        supplyId: null,
        supplyName: null,
        upLine: null,
        downLine: null,
        middleLine: null,
        stopFlag: null,
        cunchudate: null,
        productiondate: null,
        itemIdentifyCode: null,
      },
      // 表单参数
      form: {},

      // 物料导入参数
      upload: {
        // 是否显示弹出层（物料导入）
        open: false,
        // 弹出层标题（物料导入）
        title: "导入物料",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/base/iteminfo/importData"
      },

      // 表单校验
      rules: {
        /*  deptId: [
            { required: true, message: "部门id不能为空", trigger: "blur" }
          ],*/

        /*       prodLockNum: [
                 { required: true, message: "转生产数量不能为空!", trigger: "blur" },
                 { validator: valiprodLockNum,trigger: "blur" }
               ],*/
        classId: [
          {required: true, message: "请选择物料分类", trigger: "blur"},
        ],
        itemCode: [
          {required: true, message: "物料编号不能为空", trigger: "blur"},
          {validator: validateitemCode, trigger: "blur"}
        ],

        itemName: [
          {required: true, message: "物料名称能为空", trigger: "blur"},
          {validator: validateitemCode, trigger: "blur"}
        ],

        upLine: [
          {validator: validateupLine, trigger: "blur"}
        ],

        downLine: [
          {validator: validateupLine, trigger: "blur"}
        ],


      }
    };
  },
  created() {
    this.getList();
    //物料分类
    getListClass().then(response => {
      this.classOptions = response.data;
    });
    //物料大类
    getListBigClass().then(response => {
      this.classBigOptions = response.data;
    });
    getLiSupplier().then(response => {
      this.supplyOptions = response.data;
    });

  },
  methods: {
    // printt(){
    //   let LODOP = getLodop();
    //   LODOP.PRINT_INIT("");
    //   LODOP.PRINT_INITA(0,0,190,94,"");
    //   for(let i=0;i<this.jms.length;i++){
    //
    //     LODOP.NewPage();
    //     LODOP.SET_PRINT_STYLE("FontSize",8);
    //     LODOP.SET_PRINT_PAGESIZE(1,500,250,"");
    //     LODOP.ADD_PRINT_BARCODE(21,2,87,134,"QRCode",this.jms[i].itemId);
    //     LODOP.ADD_PRINT_TEXT(30,80,90,20,"产品名:"+this.jms[i].itemName);
    //     LODOP.ADD_PRINT_TEXT(65,80,90,20,"产品码:"+this.jms[i].itemId);
    //     //    LODOP.PRINT();
    //
    //   }
    //
    //
    //   LODOP.PREVIEW();
    // },
    show() {
      this.showFlag = true;
      this.selectedRows = {}
      this.selectedItemId = undefined
    },
    printtt() {
      this.$nextTick(() => {
        this.jms.forEach((item, index) => {
          let code = item.itemId;
          this.$refs.qrCodeUrl[index].innerHTML = "";
          new QRCode(this.$refs.qrCodeUrl[index], {
            text: code, //二维码内容
            width: 90,
            height: 90,
            // colorDark: "#333333", //二维码颜色
            // colorLight: "#ffffff", //二维码背景色
          })
        })
        setTimeout(() => {
          this.priDan2()
        }, 200)
      })
    },
    priDan2() {
      // printBill
      // const style = '@page{margin:0};.title{fontSize:30px}'
      const style = '@page { margin:0 } ' + '@media print { #title{ font-size:40px};#title1{ font-size:40px }  ';
      printJS({
        printable: this.$refs.printDan2,
        type: 'html',
        header: '',
        targetStyles: ['*'],
        scanStyles: false,
        style: style,
        onPrintDialogClose: () => {
          console.log('弹窗关闭');
        },
        onLoadingEnd: () => {
          console.log('加载完毕')
        }
      })
    },
    printt2() {
      const id = this.ids
      getIteminfo(id).then(response => {
        console.log(response, 'ressssssss')
        let CID = response.data.classId
        if (CID == 'Y' || CID == 'J') {
          this.formDan = response.data
          let data = response.data
          this.$refs.qrCodeUrl.innerHTML = "";
          var qrcode = new QRCode(this.$refs.qrCodeUrl, {
            text: data.itemId, // 需要转换为二维码的内容
            width: 120,
            height: 120,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
          })
          this.$nextTick(() => {
            this.priDan()
          })
        } else {
          this.$message.error('该物料不是原材料');
        }

      });
    },
    priDan() {
      // printBill
      // const style = '@page{margin:0};.title{fontSize:30px}'
      const style = '@page { margin:0 } ' + '@media print { #title{ font-size:40px};#title1{ font-size:40px }  ';
      printJS({
        printable: this.$refs.printDan,
        type: 'html',
        header: '',
        targetStyles: ['*'],
        scanStyles: false,
        style: style,
        onPrintDialogClose: () => {
          console.log('弹窗关闭');
        },
        onLoadingEnd: () => {
          console.log('加载完毕')
        }
      })
    },
    /** 查询物料信息列表 */
    getList() {
      this.loading = true;
      listIteminfo(this.queryParams).then(response => {
        this.iteminfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('base/iteminfo/importTemplate', {}, `物料信息模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    //大类翻译
    classFormat(row, column) {
      var actions = [];
      Object.keys(this.classOptions).some((key) => {
        if (this.classOptions[key].classId == ('' + row.classId)) {
          actions.push(this.classOptions[key].className);
          return true;
        }
      })
      return actions.join('');
    },


    //供应商翻译
    supplyFormat(row, column) {
      var actions = [];
      Object.keys(this.supplyOptions).some((key) => {
        if (this.supplyOptions[key].id == ('' + row.supplyId)) {
          actions.push(this.supplyOptions[key].supplyName);
          return true;
        }
      })
      return actions.join('');
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        itemName: null,
        unit: null,
        baozhuangType: null,
        baozhuangQty: null,
        spec: null,
        model: null,
        tmh: null,
        classId: null,
        className: null,
        supplyId: null,
        supplyName: null,
        upLine: null,
        downLine: null,
        middleLine: null,
        stopFlag: null,
        cunchudate: null,
        productiondate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.jms = selection.map((item) => {
        return {
          itemName: item.itemName,
          itemId: item.itemId,
          itemCode: item.itemCode,
          spec: item.spec
        }
      })
    },
    getClass(value) {
      let selectedName = {};
      selectedName = this.classOptions.find((item) => {
        return item.classId === value;
        //筛选出匹配数据，是对应数据的整个对象
      });
      this.form.className = selectedName.className;
    },
    getBigClass(value) {
      let selectedName = {};
      selectedName = this.classBigOptions.find((item) => {
        return item.wuliuDlCode === value;
        //筛选出匹配数据，是对应数据的整个对象
      });
      this.form.classBigName = selectedName.wuliuDlName;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getIteminfo(id).then(response => {
        this.form = response.data;
        if (response.data.lineSimpleCode) {
          this.form.lineSimpleCode = response.data.lineSimpleCode.split(",")
        }
        this.open = true;
        this.title = "修改物料信息";
      });
    },
    handleDeleteAll() {
      this.$modal.confirm('是否确认全部删除数据？').then(function () {
        return delAllItemInfo();
      }).then(() => {
        this.getList();
        this.$modal.alertSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      let multipleCode = this.form.lineSimpleCode;
      let a = "";
      for (let i = 0; i < multipleCode.length; i++) {
        if (i == multipleCode.length - 1) {
          a = a + multipleCode[i]
        } else {
          a = a + multipleCode[i] + ","
        }
      }
      this.form.lineSimpleCode = a;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateIteminfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIteminfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料信息编号为"' + ids + '"的数据项？').then(function () {
        return delIteminfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料导入";
      this.upload.open = true;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('base/iteminfo/export', {
        ...this.queryParams
      }, `iteminfo_${new Date().getTime()}.xlsx`)
    },
    handleCurrent(row) {
      if (row) {
        this.selectedRows = row;
      }
    },
    handleRowDbClick(row) {
      if (row) {
        this.selectedRows = row;
        this.$emit('onSelected', this.selectedRows);
        this.showFlag = false;
      }
    },
    // 单选选中数据
    handleRowChange(row) {
      if (row) {
        this.selectedRows = row;
      }
    },
    /** 提交按钮 */
    confirmSelect() {
      if (this.selectedItemId == null || this.selectedItemId == 0) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '请至少选择一条数据!'
        });
        return;
      }
      this.$emit('onSelected', this.selectedRows);
      this.showFlag = false;
    }
  }
};
</script>
